package com.roger.homecenterscreen.data.location

import android.annotation.SuppressLint
import android.content.Context
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.Looper
import android.util.Log
import kotlinx.coroutines.*
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withTimeoutOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import com.roger.homecenterscreen.data.network.NetworkModule
import com.roger.homecenterscreen.config.ApiConfig
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import java.util.concurrent.TimeUnit
import android.Manifest
import android.content.pm.PackageManager
import androidx.core.content.ContextCompat

/**
 * 增强的位置服务
 * 优先使用经纬度获取城市区域名称，失败后使用IP地址
 */
class EnhancedLocationService(private val context: Context) {
    
    companion object {
        private const val TAG = "EnhancedLocationService"
    }
    
    private val locationManager: LocationManager =
        context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
    
    private val okHttpClient = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .build()
    
    /**
     * 获取当前位置，优先使用经纬度转地址，失败后使用IP地址
     */
    @SuppressLint("MissingPermission")
    suspend fun getCurrentLocationWithCityName(): Result<LocationData> {
        return try {
            Log.i(TAG, "=================== 开始位置获取流程 ===================")
            Log.i(TAG, "📍 步骤1: 检查位置权限")
            
            // 检查是否有位置权限
            val hasPermission = hasLocationPermission()
            Log.i(TAG, "🔐 位置权限状态: ${if (hasPermission) "已授权" else "未授权"}")
            
            if (hasPermission) {
                Log.i(TAG, "📍 步骤2: 尝试GPS定位")
                // 第一步：尝试获取GPS位置
                val gpsLocationResult = getGPSLocation()
                
                if (gpsLocationResult.isSuccess) {
                    val gpsLocation = gpsLocationResult.getOrNull()!!
                    Log.i(TAG, "🎯 GPS定位成功!")
                    Log.i(TAG, "📌 GPS坐标: 纬度=${gpsLocation.latitude}, 经度=${gpsLocation.longitude}")
                    
                    Log.i(TAG, "📍 步骤3: 使用GPS坐标调用cn.apihz.cn获取地址")
                    // 第二步：使用经纬度获取城市区域名称
                    val cityResult = getCityNameByCoordinates(gpsLocation.latitude, gpsLocation.longitude)
                    
                    if (cityResult.isSuccess) {
                        val cityInfo = cityResult.getOrNull()!!
                        Log.i(TAG, "🏙️ cn.apihz.cn地址解析成功!")
                        Log.i(TAG, "🏠 城市: ${cityInfo.city}")
                        Log.i(TAG, "🏢 区县: ${cityInfo.district}")
                        Log.i(TAG, "📍 完整地址: ${cityInfo.address}")
                        Log.i(TAG, "=================== 位置获取完成 (GPS路径) ===================")
                        
                        Result.success(gpsLocation.copy(
                            city = cityInfo.city,
                            district = cityInfo.district,
                            address = cityInfo.address
                        ))
                    } else {
                        Log.w(TAG, "❌ cn.apihz.cn地址解析失败: ${cityResult.exceptionOrNull()?.message}")
                        Log.i(TAG, "📍 步骤4: 降级到IP地址查询 (保留GPS坐标)")
                        // 如果经纬度转地址失败，使用IP地址作为备用
                        getLocationByIPAddress(gpsLocation)
                    }
                } else {
                    Log.w(TAG, "❌ GPS定位失败: ${gpsLocationResult.exceptionOrNull()?.message}")
                    Log.i(TAG, "📍 步骤3: 降级到IP地址查询")
                    // 如果GPS定位失败，直接使用IP地址查询
                    getLocationByIPAddressOnly()
                }
            } else {
                Log.i(TAG, "📍 步骤2: 直接使用IP地址查询 (无权限)")
                // 没有权限时直接使用IP地址查询
                getLocationByIPAddressOnly()
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "💥 位置获取流程异常", e)
            Log.e(TAG, "=================== 位置获取失败 ===================")
            Result.failure(e)
        }
    }
    
    /**
     * 获取GPS位置
     */
    @SuppressLint("MissingPermission")
    private suspend fun getGPSLocation(): Result<LocationData> {
        return try {
            Log.i(TAG, "🛰️ 开始GPS定位...")
            
            if (!isLocationEnabled()) {
                Log.w(TAG, "❌ 位置服务未开启")
                return Result.failure(Exception("位置服务未开启"))
            }
            
            // 优先使用GPS，如果不可用则使用网络定位
            val provider = when {
                locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) -> {
                    Log.i(TAG, "📡 使用GPS提供者")
                    LocationManager.GPS_PROVIDER
                }
                locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) -> {
                    Log.i(TAG, "📶 使用网络定位提供者")
                    LocationManager.NETWORK_PROVIDER
                }
                else -> {
                    Log.w(TAG, "❌ 没有可用的位置提供者")
                    return Result.failure(Exception("没有可用的位置提供者"))
                }
            }
            
            Log.i(TAG, "⏳ 等待GPS响应 (超时15秒)...")
            val location = withTimeoutOrNull(15000L) { // 15秒超时
                suspendCancellableCoroutine<Location> { continuation ->
                    val locationListener = object : LocationListener {
                        override fun onLocationChanged(location: Location) {
                            Log.i(TAG, "📍 GPS返回位置: ${location.latitude}, ${location.longitude}")
                            Log.i(TAG, "🎯 GPS精度: ${location.accuracy}米")
                            locationManager.removeUpdates(this)
                            continuation.resume(location)
                        }
                        
                        override fun onProviderEnabled(provider: String) {
                            Log.i(TAG, "✅ 位置提供者启用: $provider")
                        }
                        override fun onProviderDisabled(provider: String) {
                            Log.w(TAG, "❌ 位置提供者禁用: $provider")
                            locationManager.removeUpdates(this)
                            continuation.resumeWithException(Exception("位置提供者已禁用: $provider"))
                        }
                        override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
                            Log.d(TAG, "📊 位置提供者状态变化: $provider, 状态: $status")
                        }
                    }
                    
                    continuation.invokeOnCancellation {
                        Log.w(TAG, "⏹️ GPS定位被取消")
                        locationManager.removeUpdates(locationListener)
                    }
                    
                    try {
                        locationManager.requestLocationUpdates(
                            provider,
                            0L,
                            0f,
                            locationListener,
                            Looper.getMainLooper()
                        )
                        Log.i(TAG, "🚀 GPS定位请求已发送，等待响应...")
                    } catch (e: Exception) {
                        Log.e(TAG, "❌ GPS定位请求失败", e)
                        continuation.resumeWithException(e)
                    }
                }
            }
            
            if (location != null) {
                Log.i(TAG, "✅ GPS定位成功获取")
                Result.success(LocationData(
                    latitude = location.latitude,
                    longitude = location.longitude
                ))
            } else {
                Log.w(TAG, "⏰ GPS定位超时 (15秒)")
                Result.failure(Exception("GPS定位超时"))
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "💥 GPS定位异常", e)
            Result.failure(e)
        }
    }
    
    /**
     * 使用经纬度获取城市区域名称
     * curl "https://cn.apihz.cn/api/other/jwjuhe2.php?id=10006335&key=b609192ce2cd6a1a66dc20dafdadb161&lon=116.301444&lat=40.050923"
     */
    private suspend fun getCityNameByCoordinates(latitude: Double, longitude: Double): Result<LocationData> = withContext(Dispatchers.IO) {
        return@withContext try {
            Log.i(TAG, "🌏 开始cn.apihz.cn地址解析...")
            Log.i(TAG, "📌 输入坐标: 纬度=$latitude, 经度=$longitude")
            
            val response = NetworkModule.coordinateLocationApiService.getLocationByCoordinates(
                id = ApiConfig.COORDINATE_API_ID,
                key = ApiConfig.COORDINATE_API_KEY,
                longitude = longitude.toString(),
                latitude = latitude.toString()
            )
            
            if (response.isSuccessful) {
                // 直接使用OkHttp进行API调用，以便获取原始响应
                val apiUrl = "https://cn.apihz.cn/api/other/jwjuhe2.php?id=${ApiConfig.COORDINATE_API_ID}&key=${ApiConfig.COORDINATE_API_KEY}&lon=${longitude}&lat=${latitude}"
                Log.i(TAG, "🔗 API请求URL: $apiUrl")
                
                val request = Request.Builder()
                    .url(apiUrl)
                    .build()
                
                Log.i(TAG, "📡 发送cn.apihz.cn API请求...")
                val rawResponse = okHttpClient.newCall(request).execute()
                
                if (rawResponse.isSuccessful) {
                    val responseBody = rawResponse.body?.string()
                    Log.i(TAG, "✅ cn.apihz.cn响应成功")
                    Log.d(TAG, "📄 API原始响应: $responseBody")
                    
                    if (!responseBody.isNullOrBlank()) {
                        // 手动解析JSON
                        val code = extractJsonValue(responseBody, "code")?.toIntOrNull()
                        Log.i(TAG, "🔢 响应状态码: $code")
                        
                        if (code == 200) {
                            // 解析地址信息
                            val address = extractJsonValue(responseBody, "address") ?: ""
                            val province = extractJsonValue(responseBody, "province") ?: ""
                            val city = extractJsonValue(responseBody, "city") ?: ""
                            val county = extractJsonValue(responseBody, "county") ?: ""
                            
                            Log.i(TAG, "🗺️ 解析原始地址信息:")
                            Log.i(TAG, "   🏞️ 省份: $province")
                            Log.i(TAG, "   🏙️ 城市: $city")
                            Log.i(TAG, "   🏢 区县: $county")
                            Log.i(TAG, "   📍 完整地址: $address")
                            
                            // 处理城市名称：如果city为空，使用province作为城市
                            val finalCity = if (city.isNotEmpty()) {
                                Log.i(TAG, "🏙️ 使用city字段作为城市名: $city")
                                city
                            } else {
                                val processedProvince = province.replace("市", "").replace("省", "")
                                Log.i(TAG, "🏞️ city为空，使用province作为城市名: $province -> $processedProvince")
                                processedProvince
                            }
                            
                            val finalDistrict = county.replace("区", "").replace("县", "")
                            Log.i(TAG, "🏢 处理后的区县名: $county -> $finalDistrict")
                            
                            val finalAddress = address.ifEmpty { "$province $finalCity $finalDistrict".trim() }
                            
                            Log.i(TAG, "🎉 cn.apihz.cn地址解析完成!")
                            Log.i(TAG, "   🏠 最终城市: $finalCity")
                            Log.i(TAG, "   🏢 最终区县: $finalDistrict")
                            Log.i(TAG, "   📮 最终地址: $finalAddress")
                            
                            Result.success(LocationData(
                                latitude = latitude,
                                longitude = longitude,
                                city = finalCity,
                                district = finalDistrict,
                                address = finalAddress
                            ))
                        } else {
                            Log.w(TAG, "❌ cn.apihz.cn返回错误码: $code")
                            Result.failure(Exception("cn.apihz.cn错误: 状态码 $code"))
                        }
                    } else {
                        Log.w(TAG, "❌ cn.apihz.cn返回空响应")
                        Result.failure(Exception("cn.apihz.cn返回空响应"))
                    }
                } else {
                    Log.w(TAG, "❌ cn.apihz.cn HTTP请求失败: ${rawResponse.code}")
                    Result.failure(Exception("cn.apihz.cn HTTP错误: ${rawResponse.code}"))
                }
            } else {
                Log.w(TAG, "❌ Retrofit请求失败: ${response.code()}")
                Result.failure(Exception("Retrofit错误: ${response.code()}"))
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "💥 cn.apihz.cn地址解析异常", e)
            Result.failure(e)
        }
    }
    
    /**
     * 使用IP地址获取位置信息（保留GPS坐标）
     */
    private suspend fun getLocationByIPAddress(gpsLocation: LocationData): Result<LocationData> {
        return try {
            Log.i(TAG, "使用IP地址获取城市名称（保留GPS坐标）")
            
            val ipLocationResult = getLocationByIPAddressOnly()
            
            if (ipLocationResult.isSuccess) {
                val ipLocation = ipLocationResult.getOrNull()!!
                // 使用IP地址获取的城市名称，但保留GPS的精确坐标
                Result.success(gpsLocation.copy(
                    city = ipLocation.city,
                    district = ipLocation.district,
                    address = ipLocation.address
                ))
            } else {
                // IP地址查询也失败，使用坐标范围推断城市
                val cityFromCoords = getCityFromCoordinates(gpsLocation.latitude, gpsLocation.longitude)
                Result.success(gpsLocation.copy(
                    city = cityFromCoords,
                    district = "",
                    address = "GPS定位 $cityFromCoords"
                ))
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "IP地址获取城市名称失败", e)
            val cityFromCoords = getCityFromCoordinates(gpsLocation.latitude, gpsLocation.longitude)
            Result.success(gpsLocation.copy(
                city = cityFromCoords,
                district = "",
                address = "GPS定位 $cityFromCoords"
            ))
        }
    }
    
    /**
     * 仅使用IP地址获取位置信息
     * 新策略：IP地址获取坐标 -> cn.apihz.cn获取详细地址
     */
    private suspend fun getLocationByIPAddressOnly(): Result<LocationData> = withContext(Dispatchers.IO) {
        return@withContext try {
            Log.i(TAG, "🌐 开始IP地址定位流程...")
            
            // 第一步：获取当前设备的公网IP
            Log.i(TAG, "📡 步骤1: 获取公网IP地址")
            val ipResult = getCurrentPublicIP()
            if (ipResult.isFailure) {
                Log.w(TAG, "❌ 获取公网IP失败: ${ipResult.exceptionOrNull()?.message}")
                return@withContext Result.failure(Exception("获取公网IP失败"))
            }
            
            val ip = ipResult.getOrNull()!!
            Log.i(TAG, "✅ 获取到公网IP: $ip")
            
            // 第二步：使用包含坐标的IP地址查询服务
            Log.i(TAG, "🌍 步骤2: 使用IP地址查询坐标")
            val ipLocationResult = getLocationAndCoordinatesFromIP(ip)
            
            if (ipLocationResult.isSuccess) {
                val ipLocation = ipLocationResult.getOrNull()!!
                Log.i(TAG, "✅ IP地址查询成功")
                Log.i(TAG, "📍 IP查询结果:")
                Log.i(TAG, "   🏙️ 城市: ${ipLocation.city}")
                Log.i(TAG, "   🏢 区域: ${ipLocation.district}")
                Log.i(TAG, "   📌 坐标: ${ipLocation.latitude}, ${ipLocation.longitude}")
                
                if (ipLocation.latitude != 0.0 && ipLocation.longitude != 0.0) {
                    Log.i(TAG, "🎯 IP查询到有效坐标，调用cn.apihz.cn获取详细地址")
                    
                    // 第三步：使用IP获取的坐标，通过cn.apihz.cn获取详细城市名称
                    val coordResult = getCityNameByCoordinates(ipLocation.latitude, ipLocation.longitude)
                    
                    if (coordResult.isSuccess) {
                        val coordLocation = coordResult.getOrNull()!!
                        Log.i(TAG, "🎉 IP→坐标→cn.apihz.cn流程成功!")
                        Log.i(TAG, "🏠 最终城市: ${coordLocation.city}")
                        Log.i(TAG, "🏢 最终区县: ${coordLocation.district}")
                        Log.i(TAG, "=================== 位置获取完成 (IP路径) ===================")
                        return@withContext Result.success(coordLocation)
                    } else {
                        Log.w(TAG, "❌ cn.apihz.cn API失败: ${coordResult.exceptionOrNull()?.message}")
                        Log.i(TAG, "🔄 降级使用IP地址基本信息")
                    }
                } else {
                    Log.w(TAG, "⚠️ IP查询未返回有效坐标，直接使用IP地址基本信息")
                }
                
                // 如果cn.apihz.cn失败，使用IP地址的基本信息
                Log.i(TAG, "📍 使用IP地址基本信息作为最终结果")
                Log.i(TAG, "🏠 IP城市: ${ipLocation.city}")
                Log.i(TAG, "🏢 IP区域: ${ipLocation.district}")
                Log.i(TAG, "=================== 位置获取完成 (IP基本信息) ===================")
                return@withContext Result.success(ipLocation)
            } else {
                Log.w(TAG, "❌ 所有IP地址服务都失败: ${ipLocationResult.exceptionOrNull()?.message}")
                Log.e(TAG, "=================== 位置获取失败 (IP路径) ===================")
                return@withContext Result.failure(Exception("无法获取IP位置信息"))
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "💥 IP地址查询流程异常", e)
            Log.e(TAG, "=================== 位置获取失败 (异常) ===================")
            Result.failure(e)
        }
    }
    
    /**
     * 使用IP地址获取位置和坐标信息
     * 尝试多个包含坐标的IP地址查询服务
     */
    private suspend fun getLocationAndCoordinatesFromIP(ip: String): Result<LocationData> = withContext(Dispatchers.IO) {
        return@withContext try {
            // 尝试多个包含坐标信息的IP地址查询服务
            val ipServices = listOf(
                "http://ip-api.com/json/$ip?fields=status,country,regionName,city,lat,lon",
                "https://ipapi.co/$ip/json/",
                "http://www.geoplugin.net/json.gp?ip=$ip"
            )
            
            for (service in ipServices) {
                try {
                    Log.i(TAG, "尝试IP地址服务: $service")
                    
                    val request = Request.Builder()
                        .url(service)
                        .build()
                    
                    val response = okHttpClient.newCall(request).execute()
                    
                    if (response.isSuccessful) {
                        val responseBody = response.body?.string()
                        if (!responseBody.isNullOrBlank()) {
                            val locationData = parseIPLocationResponse(service, responseBody)
                            if (locationData != null) {
                                Log.i(TAG, "IP地址服务成功: ${locationData.city} (${locationData.latitude}, ${locationData.longitude})")
                                return@withContext Result.success(locationData)
                            }
                        }
                    }
                } catch (e: Exception) {
                    Log.w(TAG, "IP服务 $service 失败", e)
                    continue
                }
            }
            
            // 如果所有包含坐标的服务都失败，使用默认位置（广东省佛山市南海区）
            Log.i(TAG, "所有定位服务都失败，使用默认位置")
            return@withContext Result.success(LocationData(
                latitude = 23.0268,
                longitude = 113.1617,
                city = "佛山市",
                district = "南海区",
                address = "广东省佛山市南海区"
            ))
            
        } catch (e: Exception) {
            Result.failure(e)
        }
    }
    
    /**
     * 解析不同IP地址服务的响应
     */
    private fun parseIPLocationResponse(service: String, responseBody: String): LocationData? {
        return try {
            when {
                service.contains("ip-api.com") -> {
                    // ip-api.com JSON响应格式
                    if (responseBody.contains("\"status\":\"success\"")) {
                        val lat = extractJsonValue(responseBody, "lat")?.toDoubleOrNull() ?: 0.0
                        val lon = extractJsonValue(responseBody, "lon")?.toDoubleOrNull() ?: 0.0
                        val city = extractJsonValue(responseBody, "city") ?: ""
                        val regionName = extractJsonValue(responseBody, "regionName") ?: ""
                        val country = extractJsonValue(responseBody, "country") ?: ""
                        
                        LocationData(
                            latitude = lat,
                            longitude = lon,
                            city = city,
                            district = regionName,
                            address = "$country $regionName $city".trim()
                        )
                    } else null
                }
                service.contains("ipapi.co") -> {
                    // ipapi.co JSON响应格式
                    val lat = extractJsonValue(responseBody, "latitude")?.toDoubleOrNull() ?: 0.0
                    val lon = extractJsonValue(responseBody, "longitude")?.toDoubleOrNull() ?: 0.0
                    val city = extractJsonValue(responseBody, "city") ?: ""
                    val region = extractJsonValue(responseBody, "region") ?: ""
                    val country = extractJsonValue(responseBody, "country_name") ?: ""
                    
                    LocationData(
                        latitude = lat,
                        longitude = lon,
                        city = city,
                        district = region,
                        address = "$country $region $city".trim()
                    )
                }
                service.contains("geoplugin.net") -> {
                    // geoplugin.net JSON响应格式
                    val lat = extractJsonValue(responseBody, "geoplugin_latitude")?.toDoubleOrNull() ?: 0.0
                    val lon = extractJsonValue(responseBody, "geoplugin_longitude")?.toDoubleOrNull() ?: 0.0
                    val city = extractJsonValue(responseBody, "geoplugin_city") ?: ""
                    val region = extractJsonValue(responseBody, "geoplugin_region") ?: ""
                    val country = extractJsonValue(responseBody, "geoplugin_countryName") ?: ""
                    
                    LocationData(
                        latitude = lat,
                        longitude = lon,
                        city = city,
                        district = region,
                        address = "$country $region $city".trim()
                    )
                }
                else -> null
            }
        } catch (e: Exception) {
            Log.w(TAG, "解析IP响应失败: $service", e)
            null
        }
    }
    
    /**
     * 从JSON字符串中提取指定字段的值
     */
    private fun extractJsonValue(json: String, key: String): String? {
        return try {
            val pattern = "\"$key\"\\s*:\\s*\"?([^,}\"]+)\"?".toRegex()
            val matchResult = pattern.find(json)
            matchResult?.groupValues?.get(1)?.replace("\"", "")
        } catch (e: Exception) {
            null
        }
    }

    /**
     * 获取当前设备的公网IP地址
     */
    private suspend fun getCurrentPublicIP(): Result<String> = withContext(Dispatchers.IO) {
        return@withContext try {
            // 尝试多个IP查询服务
            val ipServices = listOf(
                "https://api.ipify.org",
                "https://ifconfig.me/ip",
                "https://ipinfo.io/ip"
            )
            
            Log.i(TAG, "🔍 尝试从${ipServices.size}个IP服务获取公网IP...")
            
            for ((index, service) in ipServices.withIndex()) {
                try {
                    Log.i(TAG, "📡 尝试IP服务 ${index + 1}/${ipServices.size}: $service")
                    
                    val request = Request.Builder()
                        .url(service)
                        .build()
                    
                    val response = okHttpClient.newCall(request).execute()
                    
                    if (response.isSuccessful) {
                        val ip = response.body?.string()?.trim()
                        if (!ip.isNullOrBlank() && isValidIP(ip)) {
                            Log.i(TAG, "✅ 获取公网IP成功: $ip (来源: $service)")
                            return@withContext Result.success(ip)
                        } else {
                            Log.w(TAG, "⚠️ IP格式无效: $ip (来源: $service)")
                        }
                    } else {
                        Log.w(TAG, "❌ IP服务响应失败: ${response.code} (来源: $service)")
                    }
                } catch (e: Exception) {
                    Log.w(TAG, "❌ IP服务 $service 请求异常: ${e.message}")
                    continue
                }
            }
            
            Log.w(TAG, "❌ 所有IP服务都无法获取公网IP")
            Result.failure(Exception("所有IP服务都无法获取公网IP"))
            
        } catch (e: Exception) {
            Log.e(TAG, "💥 获取公网IP异常", e)
            Result.failure(e)
        }
    }
    
    /**
     * 验证IP地址格式
     */
    private fun isValidIP(ip: String): Boolean {
        return try {
            val parts = ip.split(".")
            if (parts.size != 4) return false
            
            parts.all { part ->
                val num = part.toIntOrNull()
                num != null && num in 0..255
            }
        } catch (e: Exception) {
            false
        }
    }
    
    /**
     * 检查位置服务是否启用
     */
    private fun isLocationEnabled(): Boolean {
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
                locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
    }
    
    /**
     * 检查是否有位置权限
     */
    private fun hasLocationPermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            context,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED ||
        ContextCompat.checkSelfPermission(
            context,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ) == PackageManager.PERMISSION_GRANTED
    }
    
    /**
     * 根据坐标获取城市名称（最后的备用方案）
     * 注意：这是最后的降级方案，应该优先使用cn.apihz.cn API
     */
    private fun getCityFromCoordinates(lat: Double, lon: Double): String {
        // 简化逻辑，只保留几个主要城市的精确范围
        // 其他情况都返回"坐标定位"，强制使用API获取
        return when {
            // 只保留核心一线城市的精确坐标范围
            lat in 39.85..40.05 && lon in 116.25..116.45 -> "北京市"  // 北京市中心
            lat in 31.15..31.35 && lon in 121.35..121.55 -> "上海市"  // 上海市中心
            lat in 23.05..23.25 && lon in 113.15..113.35 -> "广州市"  // 广州市中心
            lat in 22.45..22.65 && lon in 114.00..114.20 -> "深圳市"  // 深圳市中心
            else -> "坐标定位"  // 其他情况强制使用API
        }
    }
} 